<template>
    <div class="content">
        <Form :label-width="200" :model="form" :rules="rules" ref="form" @submit.native.prevent>
            <FormItem label="案例名称" prop="caseName">
                <Input
                    placeholder="3-15位,不可重复"
                    v-model="form.caseName"
                ></Input>
            </FormItem>
            <Permission value="2,3">
                <FormItem label="是否公开" prop="pubFlag" required>
                    <RadioGroup v-model="form.pubFlag">
                        <Radio :label="0">私有</Radio>
                        <Radio :label="1">公开（公开案例校内所有老师可用）</Radio>
                    </RadioGroup>
                </FormItem>
            </Permission>
            <FormItem class="anliCate" label="案例分类" prop="caseType">
                <!-- <RadioGroup v-model="form.caseType" >
                    <Radio
                        v-for="item in caseTypeList"
                        :key="item.value"
                        :label="item.value"
                    >
                        <span>{{ item.label }}</span>
                    </Radio>
                </RadioGroup> -->
                <Radio-group v-model="form.radio">
                    <Radio :label="2">
                        <span>制单</span>
                    </Radio>
                    <i-select :model.sync="model1" style="width:150px">
                        <i-option v-for="item in makeList" :key="item.value" :value="item.value">{{ item.label }}</i-option>
                    </i-select>
                    <Radio :label="3">
                        <span>实操</span>
                    </Radio>
                    <el-cascader
                        v-model="cascader"
                        size="small"
                        :options="options"
                        filterable
                    >
                    </el-cascader>
                </Radio-group>
            </FormItem>
            <FormItem label="案例资料" prop="caseInfoList">
                <FileListUpload
                    v-model="form.caseInfoList"
                    :accept="accept"
                    :format="format"
                    :maxSize="20480"
                >
                </FileListUpload>
            </FormItem>
            <FormItem class="w400" label="考察重点" prop="answer">
                <CheckboxGroup v-model="form.answer" @on-change="handleTypeChange">
                    <!-- {{answerList}} -->
                    <Checkbox
                        :disabled="item.value === requiredValue"
                        class="m100"
                        v-for="(item) in answerList"
                        :key="item.value"
                        :label="item.value"
                    >
                        <span>
                            {{ item.label }}
                        </span>
                    </Checkbox>
                    <Icon type="ios-help-circle-outline" title="请为本案例考察的内容设置参考答案；将根据参考答案对学生提交的单据进行评分。" />
                </CheckboxGroup>
            </FormItem>
            <FormItem
                v-for="(item, i) in form.caseAnswerList"
                v-show="form.answer.includes(item.answerType)"
                :key="item.answerType"
                :label="declareList[item.answerType]"
                :label-width="260"
                :rules="fileRule"
                :prop="`caseAnswerList.${i}`"
            >
                <div>
                    <div class="answer-file">
                        <div class="file-name">{{ item.answerName | formatFile }}</div>
                        <div>请按模版要求填写：<a @click="download(item.answerType)">下载模版</a></div>
                    </div>
                    <Upload
                        class="answer-upload-btn"
                        :action="action"
                        :headers="headers"
                        :accept="accept"
                        :format="format"
                        :maxSize="20480"
                        :on-format-error="onFormatError"
                        :on-exceeded-size="onExceededSize"
                        :on-success="res => onUploadSuccess(res, i)"
                        :show-upload-list="false"
                    >
                        <Button>选择文件</Button>
                    </Upload>
                </div>
            </FormItem>
            <FormItem>
                <div class="submit-footer">
                    <Button type="primary" @click="submit">保存</Button>
                    <Button @click="handleCancel">取消</Button>
                </div>
            </FormItem>
        </Form>
    </div>
</template>
<script>

import { mapMutations } from 'vuex'
import FileListUpload from './components/file-list-upload'
import { getToken } from '@/libs/util'
import { anliType, declareTypes } from '@/libs/enums'
import { caseAdd, caseUpdate, queryCaseInfo } from '@/api/caseManage'
import { downloadTemplate } from '@/api/fileManage'
import { downloadURL } from '@/config/downloadUrl.js'
const caseTypeList = Object.keys(anliType).map(k => {
    return { label: anliType[k], value: k }
})
// console.log(declareTypes)
const answersList = [
    { label: '进口报关单', value: '1' },
    { label: '出口报关单', value: '2' },
    { label: '进境报关单', value: '3' },
    { label: '出境报关单', value: '4' },
    { label: '核注清单(进口)', value: '5' },
    { label: '核注清单(出口)', value: '6' },
    { label: '公路舱单', value: '7' },
    { label: '海运舱单', value: '8' },
    { label: '一般原产地证', value: '9' },
    { label: '普惠制原产地证', value: '10' },
    { label: '东盟自贸区原产地证', value: '11' },
    { label: '亚太自贸区原产地证', value: '12' }

]
const dyData = {
    '1': 7,
    '2': 7,
    '3': 7,
    '4': 7,
    '5': 4,
    '6': 4,
    '7': 6,
    '8': 5
}

export default {
    components: {
        FileListUpload
    },
    data () {
        const checkArray = (rule, value, cb) => {
            Array.isArray(value) && value.length > 0
                ? cb()
                : cb(new Error(rule.message || ''))
        }
        const fileRule = Object.freeze({
            required: true,
            message: '请上传文件',
            trigger: 'change',
            validator: (rule, value, cb) => {
                this.form.answer.includes(value.answerType) && !value.answerName ? cb(new Error(rule.message)) : cb()
            }
        })
        return {
            cascader: '',
            phone: '2',
            accept: '.doc,.docx,.xls,.xlsx,.pdf',
            format: Object.freeze(['pdf', 'xls', 'xlsx', 'doc', 'docx']),
            headers: Object.freeze({
                Authorization: getToken()
            }),
            action: downloadURL + '/fileManage/upload',
            caseTypeList: Object.freeze(caseTypeList),
            declareList: Object.freeze(declareTypes),
            answerList: answersList,
            requiredValue: '',
            form: {
                radio: '',
                caseId: '',
                pubFlag: 1,
                caseName: '',
                caseType: '',
                caseInfoList: [],
                answer: [],
                caseAnswerList: []
            },
            options: [
                {
                    value: 'exportGoods',
                    label: '一般出口货物',
                    children: [{
                        value: 'originCerti',
                        label: '原产地证'
                    },
                    {
                        value: 'goodsExPrac',
                        label: '一般货物出口业务练习'
                    }]
                },
                {
                    value: 'importGoods',
                    label: '一般出口货物',
                    children: [{
                        value: 'imLicence',
                        label: '进口许可证'
                    }]
                },
                {
                    value: 'taxMakesGoods',
                    label: '保税加工货物',
                    children: [{
                        value: 'exGoodsWorks',
                        label: '出口成品业务'
                    }]
                },
                {
                    value: 'reductionTaxGoods',
                    label: '特定减免税货物',
                    children: [{
                        value: 'taxDeclare',
                        label: '减免税申请'
                    }]
                },
                {
                    value: 'imExgoods',
                    label: '暂准进出境货物',
                    children: [{
                        value: 'imBorder',
                        label: '暂准进出境货物-进境'
                    }]
                },
                {
                    value: 'praticalTraining',
                    label: '综合实训',
                    children: [{
                        value: 'taxMakesWorks',
                        label: '保税加工整笔业务'
                    }]
                }
            ],
            model1: '',
            makeList: [
                {
                    value: 'ckLicence',
                    label: '出口许可证'
                },
                {
                    value: 'jkLicenceEl',
                    label: '自动进口许可证-机电'
                },
                {
                    value: 'jkLicence',
                    label: '自动进口许可证-非机电'
                },
                {
                    value: 'goodsJk',
                    label: '一般货物进口报关'
                },
                {
                    value: 'goodsCk',
                    label: '一般货物出口报关'
                },
                {
                    value: 'taxReduction',
                    label: '减免税申请'
                },
                {
                    value: 'specialGoogsJk',
                    label: '特定减免货物进口报关'
                },
                {
                    value: 'elecDeclare',
                    label: '电子报关委托书'
                },
                {
                    value: 'originLicence',
                    label: '一般原产地证'
                },
                {
                    value: 'phLicence',
                    label: '普惠制原产地证'
                },
                {
                    value: 'eastTradeLicence',
                    label: ' 东盟自贸区原产地证'
                },
                {
                    value: 'AsiaTradeLicence',
                    label: '亚太自贸区原产地证'
                },
                {
                    value: 'tradeApp',
                    label: '加工贸易手册申请'
                },
                {
                    value: 'tradeVerify',
                    label: '加工贸易手册报核'
                },
                {
                    value: 'materialJk',
                    label: '料件进口报关'
                },
                {
                    value: 'finishedCk',
                    label: '成品出口报关'
                }
            ],
            rules: Object.freeze({
                caseName: [
                    { required: true, message: '案例名称必填', trigger: 'blur' },
                    { min: 3, max: 15, message: '3-15位,不可重复', trigger: 'blur,change' }
                ],
                caseType: [
                    { required: true, message: '案例类型必填', trigger: 'blur' }
                ],
                caseInfoList: [
                    { required: true, message: '案例资料必填', validator: checkArray, trigger: 'change' }
                ],
                answer: [
                    { required: true, message: '参考答案必填', validator: checkArray, trigger: 'change' }
                ]
            }),
            fileRule: fileRule
        }
    },
    watch: {
        cascader (val) {
            if (val[1] === 'goodsExPrac') {
                this.requiredValue = '1'
                this.form.answer.push('1')
            }
        }
    },
    created () {
        this.initData()
    },
    inject: ['nextPageReload'],
    methods: {
        ...mapMutations(['removeTagNav']),
        download (type) {
            let a = dyData[type.toString()]
            downloadTemplate({
                fileFlag: a
            })
        },
        handleTypeChange (v) {
            console.log(v)
            /* const caseAnswerList = []
            this.answerList = (answers[v] || []).map(item => {
                const { label, value } = item
                caseAnswerList.push({
                    answerType: value,
                    answerName: ''
                })
                return { label, value }
            })
            this.form.answer = []
            this.form.caseAnswerList = caseAnswerList.slice() */
            // console.log(this.form.answer)
            // console.log(this.answerList)
            this.form.caseAnswerList = []
            this.answerList.map((item, index) => {
                // if(this.form.answer.includes(index)){
                let { value } = item
                this.form.caseAnswerList.push({
                    answerType: value,
                    answerName: ''
                })

                // }
            })
            // console.log(this.form.caseAnswerList)
        },
        onFormatError () {
            this.$Message.error('文件格式有误')
        },
        onExceededSize () {
            this.$Message.error('文件大小超出可上传范围')
        },
        onUploadSuccess (res, i) {
            if (res.code === '0000') {
                const data = res.data || +new Date()
                if (data && this.form.caseAnswerList[i]) {
                    this.form.caseAnswerList[i].answerName = data
                }
            } else {
                this.$Message.error(res.msg)
            }
        },
        initData () {
            this.form.caseType = this.caseTypeList[0].value
            this.handleTypeChange(this.form.caseType)
            const id = this.$route.params.id
            if (id) {
                queryCaseInfo(id).then(res => {
                    if (res.data.code === '0000') {
                        const keys = ['caseId', 'caseName', 'caseType']
                        const data = res.data.data
                        // 根据caseType设置 参考答案选项
                        this.form.caseType !== data.caseType && this.handleTypeChange(data.caseType)
                        keys.forEach(k => {
                            this.form[k] = data[k]
                        })
                        this.form.pubFlag = !data.pubFlag ? 0 : 1
                        // 案例资料
                        this.form.caseInfoList = data.infoDtoList.map(item => {
                            return {
                                file: item.infoName
                            }
                        })
                        // 参考答案
                        const answer = []
                        data.answerInfoDtoList.forEach(item => {
                            const type = item.answerType
                            answer.push(type)
                            const target = this.form.caseAnswerList.find(item => item.answerType === type)
                            if (target) {
                                target.answerName = item.answerName
                            }
                        })
                        this.form.answer = answer
                    } else {
                        this.$Message.error(res.data.data || res.data.msg)
                    }
                })
            }
        },
        submit () {
            this.$refs.form.validate(v => {
                if (v) {
                    const { answer, caseAnswerList, caseInfoList, pubFlag } = this.form
                    const fileList = caseAnswerList.filter(item => answer.includes(item.answerType))
                    const data = Object.assign(
                        {},
                        this.form,
                        {
                            caseInfoList: caseInfoList.map(item => {
                                return {
                                    infoId: item.id,
                                    infoName: item.file
                                }
                            }),
                            caseAnswerList: fileList,
                            pubFlag: pubFlag === 1
                        }
                    )
                    const fn = this.form.caseId ? caseUpdate : caseAdd
                    fn(data).then(res => {
                        if (res.data.code === '0000') {
                            this.$Message.success('保存成功')
                            this.handleCancel()
                        } else {
                            this.$Message.error(res.data.msg)
                        }
                    })
                }
            })
        },
        handleCancel () {
            this.removeTagNav(this.$route)
            this.nextPageReload()
            this.$router.replace({
                name: 'caseManageList'
            })
        }
    }
}
</script>
<style lang="less" scoped>
.ivu-form {
    max-width: 800px;
}
.answer-upload-btn {
    display: inline-block;
    vertical-align: top;
}
.answer-file{
    &:extend(.answer-upload-btn);
    padding: 0 10px;
    .file-name {
        width: 300px;
        height: 33px;
        border: 1px solid #ccc;
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: normal;
        padding: 0 10px;
    }
}
.w400 .ivu-checkbox-group{
    width:550px;
}
.m100{
    min-width: 110px;
    margin-right:10px;
}
.ivu-radio-wrapper{
    margin-right: 30px;
}
.ivu-select{
    margin-left: 10px;
}
.anliCate .ivu-radio-wrapper{
    margin: 0;
}
.anliCate .ivu-select{
    margin-right: 30px;
}
</style>
